package com.songlanyun.filter;

import com.alibaba.fastjson.JSON;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.utils.RedisKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 限流 防止流读取一次后就没有了, 所以需要将流继续写出去
 */
//@Order(1)
//@WebFilter(
//        filterName = "limitFilter",
//        urlPatterns = {"/*"})
//public class LimitFilter
//        implements Filter {
//    @Autowired
//    RedisTemplate<String, String> redisTemplate;
//
//    @Value("${limit.time}")
//    long time;
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        RequestReaderHttpServletRequestWrapper requestWrapper = new RequestReaderHttpServletRequestWrapper(request);
//        // header方式
//        String token = request.getHeader("token");
//        // String uri = request.getRequestURI().toString();
//        String url = request.getRequestURI() + "?" + request.getQueryString();
//        String redisKey = RedisKeys.getLimitKey(token + ":" + url);
//        String value = redisTemplate.opsForValue().get(redisKey);
//        String body = requestWrapper.getBodyString(requestWrapper);
//
//        if (body.equals(value)) {
//            servletResponse.setContentType("application/json;charset=utf-8");
//            R responseBean = R.error(-410, "操作频繁");
//            servletResponse.getWriter().write(JSON.toJSONString(responseBean));
//            return;
//        }
//        redisTemplate.opsForValue().set(redisKey, body, time, TimeUnit.MILLISECONDS);
//        filterChain.doFilter(requestWrapper, servletResponse);
//    }
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//    }
//
//    @Override
//    public void destroy() {
////    }
//}
